import { takeEvery,put  } from 'redux-saga/effects'
import { addProductToCart, addProductToLocalCart, changeLocalProductNumber, changeServiceProductNumber, deleteProductFromLocalCart, loadCarts, saveCarts } from '../actions/cart.actions'
import axios from 'axios'

// 将商品添加到购物车中
function* handleAddProductToCart(actions){
  const { data } = yield axios.post('http://localhost:3005/cart/add',{gid: actions.payload})
  yield put(addProductToLocalCart(data))
}

function* handleLoadCarts(){
  const { data } = yield axios.get('http://localhost:3005/cart')
  yield put(saveCarts(data))
}

function* handleDeleteProductFromLocalCart(actions){
  const { data } = yield axios.delete('http://localhost:3005/cart/delete',{ 
    params: {
      cid: actions.payload
    }
  })
  yield put(deleteProductFromLocalCart(data.index))
}

function* handleChangeServiceProductNumber(action) {
  const { data } = yield axios.put('http://localhost:3005/cart', action.payload)
  yield put(changeLocalProductNumber(data))
}

export default function* cartSaga(){
  // 将商品添加到购物车中
  yield takeEvery(addProductToCart, handleAddProductToCart)

  yield takeEvery(loadCarts, handleLoadCarts)

  yield takeEvery(deleteProductFromLocalCart, handleDeleteProductFromLocalCart)

  yield takeEvery(changeServiceProductNumber,handleChangeServiceProductNumber)
}